package com.cskaoyan.service;

import com.cskaoyan.bean.MarketStorage;
import com.cskaoyan.bean.MarketStorageExample;
import com.cskaoyan.bean.common.BaseRespVo;
import com.cskaoyan.bean.common.CommonData;
import com.cskaoyan.mapper.MarketStorageMapper;
import com.cskaoyan.util.ConfigPropertiesUtil;
import com.cskaoyan.util.LocalStorage;
import com.cskaoyan.util.StringUtil;
import com.cskaoyan.util.TransactionUtil;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.session.SqlSession;

import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author Yuye Wang
 * @date 2023/5/30 11:28
 * @description TODO
 */
public class StorageServiceImpl implements StorageService {

    @Override
    public BaseRespVo create(InputStream inputStream, long size, String contentType, String fileName) {
        TransactionUtil.startTransaction();
        SqlSession sqlSession = TransactionUtil.getSqlSession();
        MarketStorageMapper marketStorageMapper = sqlSession.getMapper(MarketStorageMapper.class);
        String key = generateKey(fileName);
        String url = generateUrl(key);

        //保存文件
        new LocalStorage().store(inputStream, size, contentType, key);

        //构造文件对象
        MarketStorage marketStorage = new MarketStorage();
        marketStorage.setName(fileName);
        marketStorage.setSize((int) size);
        marketStorage.setType(contentType);
        marketStorage.setUrl(url);
        marketStorage.setKey(fileName);

        //执行storage表的新增
        marketStorage.setAddTime(new Date());
        marketStorage.setUpdateTime(new Date());
        marketStorage.setDeleted(false);

        int updateCount = marketStorageMapper.insertSelective(marketStorage);

        //返回响应对象
        if (updateCount != 0) {
            TransactionUtil.commit();
            return BaseRespVo.ok(marketStorage);
        }
        return BaseRespVo.fail("文件上传失败");
    }

    @Override
    public BaseRespVo list(Integer page, Integer limit, String key, String name, String sort, String order) {
        TransactionUtil.startTransaction();
        SqlSession sqlSession = TransactionUtil.getSqlSession();
        MarketStorageMapper marketStorageMapper = sqlSession.getMapper(MarketStorageMapper.class);
        //分页
        PageHelper.startPage(page, limit);

        //构造条件子句
        MarketStorageExample example = new MarketStorageExample();
        MarketStorageExample.Criteria criteria = example.createCriteria();
        if (!StringUtil.isEmpty(key)) {
            criteria.andKeyLike("%" + key + "%");
        }
        if (!StringUtil.isEmpty(name)) {
            criteria.andNameLike("%" + name + "%");
        }
        criteria.andDeletedEqualTo(false);
        if (!StringUtil.isEmpty(sort) & !StringUtil.isEmpty(order)) {
            example.setOrderByClause(sort + " " + order);
        }

        //执行查询
        List<MarketStorage> marketStorageList = marketStorageMapper.selectByExample(example);

        TransactionUtil.commit();
        //返回响应对象
        return BaseRespVo.ok(CommonData.data(marketStorageList));
    }

    @Override
    public BaseRespVo update(MarketStorage marketStorage) {
        TransactionUtil.startTransaction();
        SqlSession sqlSession = TransactionUtil.getSqlSession();
        MarketStorageMapper marketStorageMapper = sqlSession.getMapper(MarketStorageMapper.class);
        marketStorage.setUpdateTime(new Date());
        int updateCount = marketStorageMapper.updateByPrimaryKeySelective(marketStorage);
        if (updateCount != 0) {
            sqlSession.commit();
            return BaseRespVo.ok(marketStorage);
        }
        return BaseRespVo.fail("修改对象名称失败");
    }

    @Override
    public BaseRespVo delete(MarketStorage marketStorage) {
        TransactionUtil.startTransaction();
        SqlSession sqlSession = TransactionUtil.getSqlSession();
        MarketStorageMapper marketStorageMapper = sqlSession.getMapper(MarketStorageMapper.class);

        marketStorage.setDeleted(true);
        int updateCount = marketStorageMapper.updateByPrimaryKeySelective(marketStorage);
        if (updateCount != 0) {
            sqlSession.commit();
            return BaseRespVo.ok(marketStorage);
        }
        return BaseRespVo.fail("删除对象失败");
    }

    private String generateKey(String fileName) {
        int index = fileName.lastIndexOf(".");
        String suffix = fileName.substring(index);
        return UUID.randomUUID().toString().replace("-", "") + suffix;
    }

    private String generateUrl(String key) {
        String urlPrefix = ConfigPropertiesUtil.getValue("url.prefix");
        String relativePath = ConfigPropertiesUtil.getValue("relative.path");
        return urlPrefix + relativePath + key;
    }
}
